<?php

namespace App\Http\Middleware;

use App\Jobs\SaveUserAvatar;
use App\User;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Jenssegers\Agent\Facades\Agent;
use Tymon\JWTAuth\Facades\JWTAuth;
use EasyWeChat\Foundation\Application;

class Authenticate
{
    protected $auth;

    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                if (strpos(Agent::getUserAgent(), 'MicroMessenger') !== false) {
                    $oauth_user = session('wechat.oauth_user');
                    if (isset($oauth_user['original']['errcode'])) {
                        $wechat = new Application([
                            'app_id' => env('WECHAT_APPID'),
                            'secret' => env('WECHAT_SECRET'),
                            'token' => env('WECHAT_TOKEN'),
                            'aes_key' => env('WECHAT_AES_KEY'),
                            'oauth' => [
                                'scopes' => array_map('trim', explode(',', env('WECHAT_OAUTH_SCOPES'))),
                                'callback' => $request->fullUrl(),
                            ],
                        ]);
                        return $wechat->oauth->redirect();
                    }
                    $openid = $oauth_user['id'];
                    $unionid = $oauth_user['original']['unionid'];
                    if ($user = User::where('openid', $openid)->first()) {
                    } elseif ($user = User::where('unionid', $unionid)->first()) {
                        $user->openid = $openid;
                        $user->save();
                    } else {
                        $user = new User;
                        $user->openid = $openid;
                        $user->avatar = $oauth_user['original']['headimgurl'];
                        $user->nickname = $oauth_user['nickname'];
                        $user->sex = $oauth_user['original']['sex'];
                        $user->country = $oauth_user['original']['country'];
                        $user->province = $oauth_user['original']['province'];
                        $user->city = $oauth_user['original']['city'];
                        $user->password = '';
                        $user->save();

                        dispatch(new SaveUserAvatar($user));
                    }

                    if (!$user->unionid) {
                        $user->unionid = $oauth_user['original']['unionid'];
                        $user->save();
                    }
                } else {
                    $user=User::find(1);
                   // $user = JWTAuth::parseToken()->authenticate();
                }

                $this->auth->login($user);
            }
        }

        if ($this->auth->user()->block) {
            return response()->view('layouts.message', ['message' => '您的帐号异常，请联系客服'], 200);
        }

        return $next($request);
    }
}
